package com.ayoka.utils;

import com.ayoka.Constant;
import com.ayoka.R;
import com.ayoka.base.AppContext;
import com.jcp.baselibrary.utils.MD5Util;
import com.jcp.baselibrary.utils.ToastUtil;
import com.jcp.baselibrary.utils.UIUtils;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Comparator;
import java.util.Map;
import java.util.Observable;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by jinchunping on 2019/1/24.
 */

public class WeChatManager extends Observable {

    public static final int WE_CHAT_LOGIN_START = 1;
    public static final int WE_CHAT_LOGIN_CANCEL = 2;
    public static final int WE_CHAT_LOGIN_FILED = 3;
    public static final int WE_CHAT_LOGIN_SUCCESS = 4;

    public static final int WE_CHAT_SHARE_START = 11;
    public static final int WE_CHAT_SHARE_CANCEL = 12;
    public static final int WE_CHAT_SHARE_FILED = 13;
    public static final int WE_CHAT_SHARE_SUCCESS = 14;

    public static final int WE_CHAT_PAY_START = 21;
    public static final int WE_CHAT_PAY_CANCEL = 22;
    public static final int WE_CHAT_PAY_FILED = 23;
    public static final int WE_CHAT_PAY_SUCCESS = 24;

    private volatile static WeChatManager instance;

    public static IWXAPI mWxApi;

    public static WeChatManager getInstance() {
        if (instance == null) {
            synchronized (WeChatManager.class) {
                if (instance == null) {
                    instance = new WeChatManager();
                }
            }
        }
        return instance;
    }

    /**
     * =========================================================
     * @ProjectName:
     * @ClassName: WeChatManager
     * @Description: 该app注册到微信
     * @Description: Constant.WX_APP_ID是指你应用在微信开放平台上的AppID，记得替换。
     * @Author: jincp
     * @CreateDate: 2019/3/14 13:19
     * =========================================================
     */
    private WeChatManager() {
        mWxApi = WXAPIFactory.createWXAPI(AppContext.getInstance(), Constant.WX_APP_ID);
        // 将该app注册到微信
        mWxApi.registerApp(Constant.WX_APP_ID);
    }

    /**
     * =========================================================
     *
     * @ProjectName:
     * @ClassName: WeChatManager
     * @Description: 判断微信是否安装
     * @Author: jincp
     * @CreateDate: 2019/3/14 13:19
     * =========================================================
     */
    public boolean isWXAppInstalled() {
        if (!mWxApi.isWXAppInstalled()) {
            ToastUtil.getInstance().show(UIUtils.getString(R.string.not_yet_installed_wechat));
            return false;
        }
        return true;
    }

    /**
     * =========================================================
     *
     * @ProjectName:
     * @ClassName: WeChatManager
     * @Description: 开始微信登录
     * @Author: jincp
     * @CreateDate: 2019/3/14 13:18
     * =========================================================
     */
    public void startLogin() {
        if (!isWXAppInstalled()) {
            return;
        }
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_login";
        mWxApi.sendReq(req);
        notifyWeChatOperation(WE_CHAT_LOGIN_START);
    }

    public void notifyWeChatOperation(int Operation) {
        setChanged();
        notifyObservers(Operation);
    }

    public void startPay(WeChatPayment weChatPayment) {
        if (!isWXAppInstalled()) {
            return;
        }
        PayReq request = new PayReq();
        request.appId = weChatPayment.getAppId();
        request.partnerId = weChatPayment.getPartnerId();
        request.prepayId = weChatPayment.getPrePayId();
        request.packageValue = weChatPayment.getPackageValue();
        request.nonceStr = weChatPayment.getNonceStr();
        request.timeStamp = weChatPayment.getTimeStamp();
        request.sign = weChatPayment.getPaySign();
        mWxApi.sendReq(request);
        notifyWeChatOperation(WE_CHAT_PAY_START);
    }

    public interface WeChatPayment {

        String getTimeStamp();

        String getPartnerId();

        String getPrePayId();

        String getPaySign();

        String getAppId();

        String getPackageValue();

        String getNonceStr();
    }

    /**
     * =========================================================
     *
     * @ProjectName:
     * @ClassName: WeChatManager
     * @Description: 获取微信二次签名
     * @Author: jincp
     * @CreateDate: 2019/3/14 13:10
     * =========================================================
     */
    public static String getWechatSign(WeChatPayment wechatBean) {
        SortedMap<String, String> signParams = new TreeMap<>(new Comparator<String>() {
            public int compare(String key1, String key2) {
                // 升序排序
                return key1.compareTo(key2);
            }
        });
        signParams.put("appid", wechatBean.getAppId());
        signParams.put("partner_id", wechatBean.getPartnerId());
        signParams.put("noncestr", wechatBean.getNonceStr());
        signParams.put("package", wechatBean.getPackageValue());
        signParams.put("timestamp", wechatBean.getTimeStamp());
        signParams.put("prepayid", wechatBean.getPrePayId());
        String sign = createSign(signParams);
        return sign;
    }

    /**
     * =========================================================
     *
     * @ProjectName:
     * @ClassName: WeChatManager
     * @Description: 微信支付签名算法sign
     * @Author: jincp
     * @CreateDate: 2019/3/14 13:17
     * =========================================================
     */
    @SuppressWarnings("rawtypes")
    private static String createSign(SortedMap<String, String> parameters) {
        StringBuffer mStringBuffer = new StringBuffer();
        // 所有参与传参的参数按照accsii排序（升序）
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (null != value && !"".equals(value) && !"sign".equals(key) && !"key".equals(key)) {
                mStringBuffer.append(key + "=" + value + "&");
            }
        }
        mStringBuffer.append("key=" + Constant.WX_PARENT_APP_KEY); //KEY是商户秘钥
        String sign = MD5Util.encrypt(mStringBuffer.toString()).toUpperCase();
        return sign;
    }
}
